#include "HeightMap.h"

Heightmap::Heightmap()
{
	m_pixelStep = 0;
	m_resolution = 1;
	m_heightScale = 1;
	m_widthScale = 1;
	m_lengthScale = 1;
	m_verticeCount = 0;
}

float Heightmap::Height( int flX, int flY )
{
	unsigned char* buff = &m_pixelData[0];
	// Calculate The Position In The Texture, Careful Not To Overflow
	int nPos = ( ( flX % m_resolution )  + ( ( flY % m_resolution ) * m_resolution ) ) * m_BPP;
	float flR = (float) (buff[ nPos     ]);			// Get The Red Component
	float flG = (float) (buff[ nPos + 1 ]);			// Get The Green Component
	float flB = (float) (buff[ nPos + 2 ]);			// Get The Blue Component
	return ( 0.299f * flR + 0.587f * flG + 0.114f * flB ) * m_heightScale;			// Calculate The Height Using The Luminance Algorithm
}

float Heightmap::InterpolatedHeight( float fX, float fY )
{	
	fX /= m_widthScale;
	fY /= m_lengthScale;
	float a = Height((int)fX, (int)fY);

	if( fX + 1 > m_resolution )
		return a;
	float b = Height((int)fX+1, (int)fY);
	float c = fX-(int)fX;
	float WidthValue = a + (b-a)*c;

	if( fY + 1 > m_resolution )
		return ( a + WidthValue )/2;
	b = Height((int)fX, (int)fY+1);
	c = fY-(int)fY;
	float HeightValue = a + (b-a)*c;
	
	return (WidthValue + HeightValue)/2;
}

unsigned int& Heightmap::getVerticeCount()
{
	return m_verticeCount;
}

unsigned int& Heightmap::getPixelStep()
{
	return m_pixelStep;
}

float& Heightmap::getHeightScale()
{
	return m_heightScale;
}

float& Heightmap::getLengthScale()
{
	return m_lengthScale;
}

float& Heightmap::getWidthScale()
{
	return m_widthScale;
}